package com.seecen.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.pojo.entity.User;
import com.seecen.service.UserService;
import com.seecen.mapper.UserMapper;
import com.seecen.utils.JwtHelper;
import com.seecen.utils.MD5Utils;
import com.seecen.utils.Result;
import com.seecen.utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
* @author ZLY
* @description 针对表【hm_user(用户信息表)】的数据库操作Service实现
* @createDate 2025-10-16 14:17:23
*/
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtHelper jwtHelper;
    @Override
    public Result login(User user) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        //判断账号是否存在
        wrapper.eq(User::getUsername,user.getUsername());
        User loginUser = userMapper.selectOne(wrapper);
        //比对用户是否正确
        if(loginUser == null){
            log.info("登录失败，用户不对");
            return Result.build(null, ResultCode.USERNAME_ERROR);
        }
        //比对密码是否正确
        if(ObjectUtil.isNotEmpty(user.getPassword())
        && MD5Utils.encrypt(user.getPassword()).equals(loginUser.getPassword())){
            //TODD 生成token
            String token = jwtHelper.createToken(Long.valueOf(loginUser.getUserId()));
            HashMap data = new HashMap();
            data.put("token",token);
            return Result.ok(data);
        }
        return Result.build(null,ResultCode.PASSWORD_ERROR);
    }

    @Override
    public Result getUser(String token) {
        //token是否有效
        boolean isExpiration = jwtHelper.isExpiration(token);
        if(isExpiration) Result.build(null,ResultCode.NOTLOGIN);

        Integer userId = jwtHelper.getUserId(token).intValue();
        User user = userMapper.selectById(userId);
        user.setPassword("");
        HashMap data = new HashMap();
        data.put("User",user);
        return Result.ok(data);
    }

    @Override
    public Result register(User user) {
        try {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", user.getUsername());
            User existingUser = userMapper.selectOne(queryWrapper);  // 修正为 selectOne

            if(existingUser != null) {
                return Result.build(null, ResultCode.USERNAME_USED);  // 移除参数名前缀
            }

            String encryptedPwd = MD5Utils.encrypt(user.getPassword());
            user.setPassword(encryptedPwd);
            int result = userMapper.insert(user);

            if(result > 0) {
                return Result.ok("注册成功");
            } else {
                return Result.build(null, ResultCode.DATABASE_ERROR);  // 移除参数名前缀
            }
        } catch (Exception e) {
            e.printStackTrace();  // 添加异常打印以便调试
            return Result.build(null, ResultCode.DATABASE_ERROR);  // 移除参数名前缀
        }
    }

    // 重置密码（无需验证）
    @Override
    public Result directResetPassword(String username, String newPassword) {
        // 1. 根据用户名查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper);

        if (user == null) {
            return Result.build(null, ResultCode.USERNAME_ERROR); // 用户不存在
        }

        // 2. 加密新密码并更新
        String encryptedPwd = MD5Utils.encrypt(newPassword); // 沿用项目加密方式
        user.setPassword(encryptedPwd);
        int rows = userMapper.updateById(user);

        if (rows > 0) {
            return Result.ok("密码已重置，请使用新密码登录");
        } else {
            return Result.build(null, ResultCode.SUBMISSION_FAILED); // 操作失败
        }
    }
}




